<script setup lang="ts">

import {userApi} from "@/api/user";
import type {SysUserProfile} from "@/api/user/types.ts";
import {renderIcon} from "@/utils";
import {FormInst, FormRules} from "naive-ui";

const avatarSize = 80;
const collapseLimit = 5
const nickname = ref<string>('')
const formRef = ref<FormInst | null>(null)
const formEntity = reactive<SysUserProfile>(<SysUserProfile>{roleNames: []})
const formRules = reactive<FormRules>({
  nickname: {
    required: true,
    message: '请输入昵称',
    trigger: 'blur'
  }
})

const modalShow = ref(false)
const modalFormRef = ref<FormInst | null>(null)
const modalFormEntity = reactive<{
  oldPassword: string;
  newPassword: string;
  confirmPassword: string;
}>(<{
  oldPassword: string;
  newPassword: string;
  confirmPassword: string;
}>{})
const modalFormRules = reactive<FormRules>({
  oldPassword: {
    required: true,
    message: '请输入旧密码',
    trigger: 'blur'
  },
  newPassword: {
    required: true,
    trigger: 'blur',
    validator: (rule, value) => {
      if (!modalFormEntity.newPassword) {
        return new Error('请输入新密码')
      } else if (value.length < 6) {
        return new Error('密码长度不能小于6位')
      }
      return true
    }
  },
  confirmPassword: {
    required: true,
    trigger: 'change',
    validator: (rule, value) => {
      if (!modalFormEntity.confirmPassword) {
        return new Error('请再次输入新密码')
      } else if (value !== modalFormEntity.newPassword) {
        return new Error('两次输入的密码不一致')
      }
      return true
    }
  }
})
const modalFormSubmitLoading = ref(false)

const handleClickRestPassword = () => {
  modalShow.value = true
}

onMounted(() => {
  userApi.userProfile().then(res => {
    Object.assign(formEntity, res.data)
    nickname.value = res.data.nickname
  })
})

const handleClickSubmit = () => {
  formRef.value?.validate((errors) => {
    if (!errors) {
      userApi.modifyUserProfile({nickname: formEntity.nickname}).then(_ => {
        window.$message?.success('修改成功')
        nickname.value = formEntity.nickname
      })
    }
  })
}
const handleClickRestPasswordSubmit = () => {
  modalFormSubmitLoading.value = true
  modalFormRef.value?.validate((errors) => {
    if (!errors) {
      userApi.resetPassword({
        oldPassword: modalFormEntity.oldPassword,
        newPassword: modalFormEntity.newPassword
      }).then(_ => {
        window.$message?.success('修改成功')
        modalShow.value = false
      }).finally(() => modalFormSubmitLoading.value = false)
    }
  })
}
</script>
<template>
  <n-card class="user-profile" w-fit>
    <template #header>
      <n-flex align="center" justify="center">
        <n-avatar :size="avatarSize" round>
          <component :is="renderIcon(formEntity.avatar ?? 'fluent-emoji-flat:clown-face',{size: avatarSize})"/>
        </n-avatar>
        <n-divider vertical style="height: 5em; margin: 0 1em"/>
        <n-space vertical>
          <n-h2 my0>{{ formEntity.nickname }}</n-h2>
          <n-h4 my0>{{ formEntity.deptName }}</n-h4>
          <n-p>{{ `最后登录时间为 ${formEntity.lastLoginTime}，登录IP为 ${formEntity.lastLoginIp}` }}</n-p>
          <n-space>
            <n-tag type="primary"
                   v-for="i in (formEntity.roleNames.length > collapseLimit ? collapseLimit : formEntity.roleNames.length)"
                   :bordered="false">{{ formEntity.roleNames[i - 1] }}
            </n-tag>
            <template v-if="formEntity.roleNames && formEntity.roleNames.length > collapseLimit">
              <n-popover trigger="hover">
                <template #trigger>
                  <n-tag type="info" :bordered="false">{{ `+${formEntity.roleNames.length - collapseLimit}` }}</n-tag>
                </template>
                <n-flex>
                  <n-tag type="primary" :bordered="false" v-for="i in formEntity.roleNames.length - collapseLimit">
                    {{ formEntity.roleNames[i + collapseLimit - 1] }}
                  </n-tag>
                </n-flex>
              </n-popover>
            </template>
          </n-space>
        </n-space>
      </n-flex>
    </template>
    <n-form
        ref="formRef"
        :rules="formRules"
        :model="formEntity"
        label-placement="left"
        label-width="auto"
    >
      <n-form-item label="用户名" path="username">
        <n-input v-model:value="formEntity.username" disabled/>
      </n-form-item>
      <n-form-item label="昵称" path="nickname">
        <n-input v-model:value="formEntity.nickname" clearable/>
      </n-form-item>
    </n-form>
    <template #footer>
      <n-space justify="end">
        <n-button secondary size="small" type="warning" @click="handleClickRestPassword">重置密码</n-button>
        <n-button secondary size="small" type="primary" @click="handleClickSubmit">提交</n-button>
      </n-space>
    </template>
  </n-card>
  <n-modal
      v-model:show="modalShow"
      preset="card"
      :mask-closable="false"
      w400px
      title="重置密码"
  >
    <n-form
        ref="modalFormRef"
        :rules="modalFormRules"
        :model="modalFormEntity"
    >
      <n-form-item label="旧密码" path="oldPassword">
        <n-input v-model:value="modalFormEntity.oldPassword" type="password" clearable/>
      </n-form-item>
      <n-form-item label="新密码" path="newPassword">
        <n-input v-model:value="modalFormEntity.newPassword" type="password" clearable/>
      </n-form-item>
      <n-form-item label="确认密码" path="confirmPassword">
        <n-input v-model:value="modalFormEntity.confirmPassword" type="password" clearable/>
      </n-form-item>
    </n-form>
    <template #footer>
      <n-space justify="end">
        <n-button
            secondary
            size="small"
            type="primary"
            :loading="modalFormSubmitLoading"
            @click="handleClickRestPasswordSubmit">提交
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>
<style scoped>
</style>
